#include "xftp_server_cmd.h"

#include <event2/bufferevent.h>
#include <string.h>
#include <stdio.h>

#include <iostream>
using namespace std;

XFtpServerCmd::XFtpServerCmd() {
}

XFtpServerCmd::~XFtpServerCmd() {
}

// 子线程XThread event事件分发中
static void ReadCB(bufferevent *bev, void *arg) {
    XFtpServerCmd *cmd = (XFtpServerCmd*)arg;
    char data[1024] = {0};
    for (;;) {
        int len = bufferevent_read(bev, data, sizeof(data) - 1);
        if (len <= 0) break;

        data[len] = '\0';
        cout << "ReadCB recv data:" << data << flush << endl;

        // 测试代码 TODO
        if (strstr(data,"quit")) {
            bufferevent_free(bev);
            delete cmd;
            break;
        }
    }
}

static void EventCB(bufferevent *bev, short what, void *arg) {
    XFtpServerCmd *cmd = (XFtpServerCmd*)arg;
    
    // 如果对方网络断掉,或者机器死机有可能收不到BEV_EVENT_EOF数据
    if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) {
        cout << "BEV_EVENT_EOF | BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT" << endl;
        bufferevent_free(bev);
        delete cmd;
    }
}

// 初始化任务, 运行在子线程中
bool XFtpServerCmd::Init() {
    cout << "XFtpServerCmd::Init()" << endl;
    // 监听socket bufferevent
    bufferevent *bev = bufferevent_socket_new(base, sock, BEV_OPT_CLOSE_ON_FREE); 
    bufferevent_setcb(bev, ReadCB, 0, EventCB, this);
    bufferevent_enable(bev, EV_READ | EV_WRITE);

    // 添加超时
    timeval rt = {10, 0};
    bufferevent_set_timeouts(bev, &rt, 0);
    return true;
}

